CODE 83. Pow(x, n)

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2013/10/16/2013-10-16-CODE 83 Pow(x, n)/

访问原文「CODE 83. Pow(x, n)

Implement pow(x, n).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public double pow(double x, int n) {
// Note: The Solution object is instantiated only once and is reused by
// each test case.
boolean minus = false;
double result = x;
if (Math.abs(n - 0.0) < 1.0E-50) {
return 1.0;
} else if (Math.abs(x - 1.0) < 1.0E-50) {
return 1.0;
} else if (Math.abs(x + 1.0) < 1.0E-50) {
if (n % 2 == 0) {
return 1.0;
} else {
return -1.0;
}
}
if (n < 0) {
minus = true;
n = -n;
}
for (int i = 1; i < n; i++) {
result *= x;
if (Math.abs(result) < 1.0E-50) {
break;
}
}
if (minus) {
return 1 / result;
} else {
return result;
}
}
Jerky Lu wechat
欢迎加入微信公众号